﻿using Kingdee.BOS.App.Core;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.Metadata;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Window;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Util;
using System.ComponentModel;
using Kingdee.BOS.App.Data;
using System.Data;

namespace LiMinCRMPlugin
{
    [Description("【服务插件】保存后自动提交审核"), HotUpdate]
    public  class AutoSubmitAuditForSave : AbstractOperationServicePlugIn
    {
        public override void AfterExecuteOperationTransaction(AfterExecuteOperationTransaction e)
        {
            base.AfterExecuteOperationTransaction(e);
            var saveResult = this.OperationResult;      
            // 筛选出保存成功的单据内码
            var successPKs = saveResult.OperateResult.Where(o => o.SuccessStatus == true).Select(x => x.PKValue).Distinct().ToArray();
            if (successPKs.Length == 0)
            {
                // 没有保存成功的结果，直接退出
                return;
            }
            string sql = @"/*dialect*/ select F_RDLV_CreatorId_6oq from RDLV_t_PendingCollection 
                             where FID='" + successPKs[0] + "'";
            DataTable dt = DBUtils.ExecuteDataSet(this.Context, sql).Tables[0];
            string creator = "";
            if (dt != null && dt.Rows.Count > 0)
            {
                creator = dt.Rows[0]["F_RDLV_CreatorId_6oq"].ToString();
            }
            if (creator== "16394")
            {
                // 提交处理
                var submitService = new SubmitService();
                var submitResult = submitService.Submit(Context, BusinessInfo, successPKs, FormOperationEnum.Submit.ToString(), Option.Copy());
                var isExit = CheckResult(saveResult, submitResult);
                saveResult.MergeResult(submitResult);
                if (isExit)
                {
                    // 有提交失败的结果，直接退出
                    return;
                }
                // 审核处理
                // 再次筛选中保存成功并且提交也成功的结果
                successPKs = saveResult.OperateResult.Where(o => o.SuccessStatus == true).Select(x => x.PKValue).Distinct().ToArray();
                if (successPKs.Length == 0)
                {
                    // 没有提交成功的结果，直接退出
                    return;
                }
                var paras = new List<object>() { "1" }; //审核所需参数
                var auditPKs = successPKs.Select(x => new KeyValuePair<object, object>(x, "")).ToList();
                var statusService = new SetStatusService();
                var auditResult = statusService.SetBillStatus(Context, BusinessInfo, auditPKs, paras, FormOperationEnum.Audit.ToString(), Option.Copy());
                isExit = CheckResult(saveResult, auditResult);
                saveResult.MergeResult(auditResult);
                if (isExit)
                {
                    // 有审核失败的结果，直接退出
                    return;
                }
                // 操作完成后刷新单据状态数据
                var billStatusField = this.BusinessInfo.GetBillStatusField();
                var billStatusPropertyName = billStatusField.PropertyName;
                var objs = new BusinessDataReader(Context).Load(e.DataEntitys.Select(o => o[0]).ToArray()
                    , BusinessInfo.GetSubBusinessInfo(new List<string>(new[] { billStatusField.Key })).GetDynamicObjectType());
                foreach (var obj in objs)
                {
                    var saveObj = e.DataEntitys.FirstOrDefault(o => o[0].ToString() == obj[0].ToString());
                    if (saveObj != null)
                    {
                        saveObj[billStatusPropertyName] = obj[billStatusPropertyName];
                    }
                }
            }
          
        }
        /// <summary>
        /// 检查操作结果，判断是否需要退出
        /// </summary>
        /// <param name="saveResult"></param>
        /// <param name="nextResult"></param>
        /// <returns></returns>
        private bool CheckResult(IOperationResult saveResult, IOperationResult nextResult)
        {
            if (nextResult == null)
            {
                saveResult.IsSuccess = false;
                return true;
            }
            if (!nextResult.IsSuccess)
            {
                // 操作失败
                saveResult.IsSuccess = false;
                return true;
            }
            if (nextResult.InteractionContext != null)
            {
                // 交互异常
                saveResult.IsSuccess = false;
                return true;
            }
            var failResults = nextResult.OperateResult.Where(e => e.SuccessStatus == false).ToArray();
            if (failResults.Length > 0 || nextResult.ValidationErrors.Count > 0)
            {
                // 操作异常，校验异常
                saveResult.IsSuccess = false;
                return true;
            }
            return false;
        }
    }
}
